from datetime import datetime
import os, websockets, asyncio, json, random
from db import SchedulesDB

class ScheduleTaskController:
  def __init__(self):
    self.websocket_client = None

  def get_ws_uri(self):
    ws_port = os.getenv("PORT", "8888")
    return f"ws://localhost:{ws_port}/websocket"
    
  async def create_websocket_client(self):
    uri = self.get_ws_uri()
    async with websockets.connect(uri) as websocket:
      self.websocket_client = websocket
      while True:
        try:
          message = await websocket.recv()
          # print(f"收到消息: {message}")
        except websockets.exceptions.ConnectionClosed:
          # print("连接已关闭")
          break
  
  async def send_ping(self):
    while True:
      try:
          await asyncio.sleep(random.uniform(5, 10))  # 任务可以被取消
          if self.websocket_client is not None:
            await self.websocket_client.send(json.dumps({"type": "ping"}))
      except asyncio.CancelledError:
          break  # 任务被取消后退出循环
    

  async def loop_task(self):
    if self.websocket_client is None:
      asyncio.create_task(self.create_websocket_client())
      asyncio.create_task(self.send_ping())
      return
    if self.websocket_client is not None:
      await self.websocket_client.send(json.dumps({"type": "trigger_schedules"}))
    # print("定时任务执行中...%s", datetime.now().strftime("%Y-%m-%d %H:%M:%S"))